import { RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store'

export default function usePermission() {
  const userStore = useUserStore()
  return {
    accessRouter(route: RouteLocationNormalized | RouteRecordRaw) {
      // 1 route meta.requiresAuth 是否需要验证
      // 2 route meta.roles 是否配置了角色
      // 3 route meta.roles 是否含有* 就是所有角色都可以访问
      let allow = (!route.meta?.requiresAuth || !route.meta?.roles || route.meta?.roles?.includes('*') )
      if(allow){
        return allow
      }else{
        allow = userStore.role.some((roleItem) => route.meta?.roles?.includes(roleItem) ) // 4 route meta.roles 用户的role是否包含在权限里面
      }
      return allow
    },
    findFirstPermissionRoute(_routers: any, role = 'admin') {
      const cloneRouters = [..._routers]
      while (cloneRouters.length) {
        const firstElement = cloneRouters.shift()
        if (
          firstElement?.meta?.roles?.find((el: string[]) => {
            return el.includes('*') || el.includes(role)
          })
        )
          return { name: firstElement.name }
        if (firstElement?.children) {
          cloneRouters.push(...firstElement.children)
        }
      }
      return null
    },
    // You can add any rules you want
  }
}
